package com.bbzn.device.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.vo.req.FenceVO;
import com.bbzn.device.client.aspect.OperationAnnotation;
import com.bbzn.device.client.config.EmqCode;
import com.bbzn.device.client.config.EmqxMqttProperties;
import com.bbzn.device.client.config.Oauth2Constant;
import com.bbzn.device.client.constant.*;
import com.bbzn.device.client.dao.mqttsub.EmqApiPublishEntity;
import com.bbzn.device.client.dataobject.*;
import com.bbzn.device.client.dto.fence.FenceDTO;
import com.bbzn.device.client.dto.fence.FenceDeviceDTO;
import com.bbzn.device.client.exception.DefinitException;
import com.bbzn.device.client.service.*;
import com.bbzn.device.client.utils.*;
import com.bbzn.device.client.utils.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * @Author 黄志鹏
 * @Date 2021/3/16 17:11
 * @Version 1.0
 */

@RestController
@RequestMapping("/fence")
@Slf4j
public class FenceController extends BaseApiService {

    @Autowired
    private CommonService commentService;
    @Autowired
    private SystemParamByCacheService systemParamByCacheService;
    @Autowired
    private FenceService fenceService;
    @Autowired
    private FenceDeviceService fenceDeviceService;
    @Autowired
    private DeviceProcessService deviceProcessService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private PublishService publishService;
    @Resource
    private EmqxMqttProperties emqxMqttProperties;
    @Autowired
    private EmqApiService emqApiService;
    @Autowired
    @Qualifier("threadPoolExecutorForVideo")
    private Executor executor;

    /**
     * 获取围栏列表
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getFenceList", method = RequestMethod.POST)
    @OperationAnnotation(content = "查询围栏列表")
    public BaseResponse getFenceList(@RequestBody FenceVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commentService.getUserId(request);
        FenceDTO fenceDTO = new FenceDTO();
        if (null != reqVO.getPageNum()) {
            fenceDTO.setPageNum(reqVO.getPageNum());
        }
        if (null != reqVO.getPageSize()) {
            fenceDTO.setPageSize(reqVO.getPageSize());
        }
        // 模糊查詢
        //前端要求加ID
        if (OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            fenceDTO.setId(reqVO.getId());
        }
        if (OptionalBean.ofNullable(reqVO.getName()).isPresent()) {
            fenceDTO.setName(reqVO.getName());
        }
        if (OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            fenceDTO.setType(reqVO.getType());
        }
        if (!OptionalBean.ofNullable(reqVO.getImei()).isPresent()) {
            List<String> list1 = deviceProcessService.findByImeisByOperatorId(userId);
            List<String> list2 = deviceService.findByAllImeis(userId);
            list1.addAll(list2);
            fenceDTO.setImeis(list1);
        } else {
            fenceDTO.setImei(reqVO.getImei());
        }
        fenceDTO.setStartIndex((reqVO.getPageNum() - 1) * reqVO.getPageSize());

//        List<Long> userIds = deviceProcessList.stream().map(DeviceProcess::getReceiveId).collect(Collectors.toList());
//        List<Long> ids = commentService.getUserIds(userId);
//        userIds.add(userId);
//        fenceDTO.setIds(userIds);
        fenceDTO.setUserId(userId);
        PageInfo<Fence> fences = fenceService.findAllPageSelective(fenceDTO);
        return setResultSuccess(fences);
    }


    /**
     * 添加围栏
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addFence", method = RequestMethod.POST)
    @OperationAnnotation(content = "添加围栏信息")
    public BaseResponse addFence(@RequestBody FenceVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commentService.getUserId(request);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getFenceType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_FENCETYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_NAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getRadius()).isPresent() && reqVO.getFenceType() == 0) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_RADIUS_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getLon()).isPresent() && reqVO.getFenceType() == 0) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_LON_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getLat()).isPresent() && reqVO.getFenceType() == 0) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_LAT_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getPositions()).isPresent() && reqVO.getFenceType() == 1) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_POSITIONS_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        FenceDTO dto = new FenceDTO();
        dto.setName(reqVO.getName());
        int count = fenceService.findCountByAll(dto);
        if (count > 0) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_CANT_ANAGIN_NAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Fence fence = new Fence();
        BeanUtils.copyProperties(reqVO, fence);
        fence.setUserId(userId);
        if (null != reqVO.getState()) {
            fence.setState(reqVO.getState());
        } else {
            fence.setState(1);
        }
        fence.setCreateTime(DateUtil.getCurrentDate());
        fence.setCreatedBy(userName);
        fenceService.insertSelective(fence);
        filterFenceUser(reqVO.getImeis(), fence);
        systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_ADD_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    private void filterFenceUser(List<String> imeis, Fence fence) {
        if (CollectionUtils.isEmpty(imeis) || null == fence) {
            log.info("围栏新增:发送EMQ：imeis和fence为空");
            return;
        }
        List<FenceDevice> tempList = new ArrayList<>();
        List<FenceDevice> fenceUsers = imeis.stream().map(imei -> new FenceDevice(fence.getId(), imei, 0, new Date(), 1, 0)).collect(Collectors.toList());
        tempList.addAll(fenceUsers);
        for (FenceDevice fenceDevice : tempList) {
            int count = fenceDeviceService.findCountByAll(fenceDevice);
            if (count > 0) {
                fenceUsers.remove(fenceDevice);
            }
        }
        if (CollectionUtils.isEmpty(fenceUsers)) {
            log.info("围栏新增:发送EMQ：没有需要新增的围栏设备关联数据");
            return;
        }
        fenceDeviceService.batchInsert(fenceUsers);
        List<EmqApiPublishEntity> mq = new ArrayList<>();
        for (FenceDevice fenceUser : fenceUsers) {
            log.info("围栏新增:进行EMQ发送：开始-------imei：" + fenceUser.getImei());
            EmqApiPublishEntity entity = new EmqApiPublishEntity();
            entity.setQos(2);
            entity.setClientid(Oauth2Constant.CLIENT_PRE + fenceUser.getImei());
            entity.setTopics(EmqCode.sendTopic + fenceUser.getImei() + EmqCode.endTopic);
            FenceDeviceDTO deviceDTO = new FenceDeviceDTO();
            deviceDTO.setAskTime(DateUtil.getCurrentTime());
            deviceDTO.setPositions(fence.getPositions());
            deviceDTO.setCode(EmqCode.addCriminalFenceCode);
            deviceDTO.setFenceDeviceId(fenceUser.getId().toString());
            deviceDTO.setFenceId(fence.getId());
            deviceDTO.setFenceName(fence.getName());
            deviceDTO.setType(fence.getType());
            deviceDTO.setFenceType(fence.getFenceType());
            deviceDTO.setImei(fenceUser.getImei());
            deviceDTO.setLat(fence.getLat());
            deviceDTO.setLon(fence.getLon());
            deviceDTO.setRadius(fence.getRadius());
            deviceDTO.setUserId(fence.getUserId());
            deviceDTO.setPositions(fence.getPositions());
            entity.setPayload(JSON.toJSONString(deviceDTO));
            mq.add(entity);
            log.info("围栏新增:进行EMQ发送：完成-------imei：" + fenceUser.getImei());
        }
        if (CollectionUtils.isEmpty(mq)) {
            log.info("围栏新增:发送EMQ：没有可发送的数据");
            return;
        }
        String url = emqxMqttProperties.getHostUrl();
        String postUri = Oauth2Constant.EMQ_API_HTTP
                + url.substring(0, url.lastIndexOf(":")).substring(url.indexOf(":")) + Oauth2Constant.EMQ_API_PUBLISHBATCH_ADR;
        emqApiService.publishBatch(postUri, mq);
        log.info("围栏新增:发送EMQ：完成");
    }


    private void filterFenceDevice(List<String> imeis, Fence fence) {
        if (CollectionUtils.isEmpty(imeis) || null == fence) {
            log.info("围栏更新:发送EMQ：imeis和fence为空");
            return;
        }
        List<CompletableFuture<EmqApiPublishEntity>> collect = imeis.stream().parallel().map(imei -> CompletableFuture.supplyAsync(() ->
                parseEmqEntity(imei, fence), executor)).collect(Collectors.toList());
        List<EmqApiPublishEntity> temp = collect.stream().map(CompletableFuture::join).collect(Collectors.toList());
        List<EmqApiPublishEntity> mq = temp.stream().filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect) || CollectionUtils.isEmpty(mq)) {
            log.info("围栏更新:发送EMQ：没有可发送的数据");
            return;
        }
        String url = emqxMqttProperties.getHostUrl();
        String postUri = Oauth2Constant.EMQ_API_HTTP
                + url.substring(0, url.lastIndexOf(":")).substring(url.indexOf(":")) + Oauth2Constant.EMQ_API_PUBLISHBATCH_ADR;
        emqApiService.publishBatch(postUri, mq);
        log.info("围栏更新:发送EMQ：组装完成");
    }

    private EmqApiPublishEntity parseEmqEntity(String imei, Fence fence) {
        log.info("围栏更新:多线程进行EMQ发送：开始-------imei：" + imei);
        EmqApiPublishEntity entity = new EmqApiPublishEntity();
        entity.setQos(2);
        entity.setClientid(Oauth2Constant.CLIENT_PRE + imei);
        entity.setTopics(EmqCode.sendTopic + imei + EmqCode.endTopic);
        FenceDevice query = new FenceDevice();
        query.setImei(imei);
        query.setFenceId(fence.getId());
        List<FenceDevice> fenceDevices = fenceDeviceService.findByAll(query);
        if (CollectionUtils.isEmpty(fenceDevices)) {
            log.info("围栏更新:多线程进行EMQ发送：没有找到对应的FenceDevice数据-------imei：" + imei);
            return null;
        }
        FenceDeviceDTO deviceDTO = new FenceDeviceDTO();
        deviceDTO.setFenceDeviceId(fenceDevices.get(0).getId().toString());
        deviceDTO.setPositions(fence.getPositions());
        deviceDTO.setAskTime(DateUtil.getCurrentTime());
        deviceDTO.setCode(EmqCode.addCriminalFenceCode);
        deviceDTO.setFenceId(fence.getId());
        deviceDTO.setFenceName(fence.getName());
        deviceDTO.setType(fence.getType());
        deviceDTO.setFenceType(fence.getFenceType());
        deviceDTO.setImei(imei);
        deviceDTO.setLat(fence.getLat());
        deviceDTO.setLon(fence.getLon());
        deviceDTO.setRadius(fence.getRadius());
        deviceDTO.setUserId(fence.getUserId());
        deviceDTO.setPositions(fence.getPositions());
        entity.setPayload(JSON.toJSONString(deviceDTO));
        log.info("围栏更新:多线程进行EMQ发送：结束-------imei：" + imei);
        return entity;
    }

    /**
     * 更新围栏
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateFence", method = RequestMethod.POST)
    @OperationAnnotation(content = "更新围栏信息")
    public BaseResponse updateFence(@RequestBody FenceVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commentService.getUserId(request);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_NAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getRadius()).isPresent() && reqVO.getFenceType() == 0) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_RADIUS_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getLon()).isPresent() && reqVO.getFenceType() == 0) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_LON_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getLat()).isPresent() && reqVO.getFenceType() == 0) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_LAT_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getPositions()).isPresent() && reqVO.getFenceType() == 1) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_POSITIONS_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Fence fence = new Fence();
        BeanUtils.copyProperties(reqVO, fence);
        if (null != reqVO.getState()) {
            fence.setState(reqVO.getState());
        } else {
            fence.setState(1);
        }
        fence.setUpdateTime(DateUtil.getCurrentDate());
        fence.setUpdatedBy(userName);
        fenceService.updateByPrimaryKeySelective(fence);
        filterFenceDevice(reqVO.getImeis(), fence);
        systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_UPDATE_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    @RequestMapping(value = "/delFence", method = RequestMethod.POST)
    @OperationAnnotation(content = "删除围栏信息")
    public BaseResponse delFence(@RequestBody FenceVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        // 查询绑定此围栏的设备列表
        FenceDevice fenceDevice = new FenceDevice();
        fenceDevice.setFenceId(reqVO.getId());
        List<FenceDevice> fenceDevices = fenceDeviceService.findByAll(fenceDevice);
        if (CollectionUtils.isNotEmpty(fenceDevices)) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_CANT_DEL_PREFIX + language);
            return setResultSuccess(systemParam.getMassage());
        }
        fenceService.deleteByPrimaryKey(reqVO.getId());
        systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_DEL_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    @RequestMapping(value = "/unBindFence", method = RequestMethod.POST)
    @OperationAnnotation(content = "解绑围栏信息")
    public BaseResponse unBindFence(@RequestBody FenceVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_FENCEDEVICEID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_NO_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getImei()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 查询绑定此围栏的设备列表
        FenceDevice query = new FenceDevice();
        query.setFenceId(reqVO.getId());
        query.setImei(reqVO.getImei());
        List<FenceDevice> fenceDevices = fenceDeviceService.findByAll(query);
        // 发送消息 【删除犯人与围栏关联关系】
        // 组装json
        if (CollectionUtils.isEmpty(fenceDevices)) {
            systemParam = systemParamByCacheService.getValues(IotCardConstant.IOTCARD_ENUM, IotCardConstant.IOTCARD_NO_DATA_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        JSONObject data = new JSONObject();
        data.put("code", EmqCode.delCriminalFenceCode);
        // 主键id-->只有这条是接收topic需要用到的
        data.put("id", fenceDevices.get(0).getId());
        data.put("imei", fenceDevices.get(0).getImei());
        data.put("type", reqVO.getType());
        // 推送绑定围栏topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + fenceDevices.get(0).getImei() + EmqCode.endTopic);
        // 1：解绑中
        fenceDevices.get(0).setState(2);
        fenceDeviceService.updateByPrimaryKeySelective(fenceDevices.get(0));
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    @RequestMapping(value = "/addPublish", method = RequestMethod.POST)
    @OperationAnnotation(content = "重发新增围栏指令")
    public BaseResponse addPublish(@RequestBody FenceVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getAppSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Fence fence = fenceService.selectByPrimaryKey(reqVO.getId());
        FenceDeviceDTO deviceDTO = new FenceDeviceDTO();
        deviceDTO.setAskTime(DateUtil.getCurrentTime());
        deviceDTO.setCode(EmqCode.addCriminalFenceCode);
        deviceDTO.setFenceDeviceId(reqVO.getFenceDeviceId().toString());
        deviceDTO.setFenceId(fence.getId());
        deviceDTO.setFenceName(fence.getName());
        deviceDTO.setFenceType(fence.getFenceType());
        deviceDTO.setImei(reqVO.getImei());
        deviceDTO.setLat(fence.getLat());
        deviceDTO.setLon(fence.getLon());
        deviceDTO.setRadius(fence.getRadius());
        deviceDTO.setUserId(fence.getUserId());
        deviceDTO.setPositions(fence.getPositions());
        publishService.sendToMqtt(JSON.toJSONString(deviceDTO), EmqCode.sendTopic + reqVO.getImei() + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(FenceConstant.FENCE_ENUM, FenceConstant.FENCE_ADD_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * Feign暴露接口：根据条件删除围栏信息
     *
     * @param record
     * @return
     * @throws Exception
     */
    @PostMapping("/deleteFenceSelective")
    public int deleteFenceSelective(@RequestBody Fence record) throws Exception {
        return fenceService.deleteSelective(record);
    }

    /**
     * Feign暴露接口：根据条件删除围栏设备的关系表数据
     *
     * @param record
     * @return
     * @throws Exception
     */
    @PostMapping("/deleteFenceDeviceSelective")
    public int deleteFenceDeviceSelective(@RequestBody FenceDevice record) throws Exception {
        return fenceDeviceService.deleteSelective(record);
    }

    /**
     * 根据条件查询围栏信息
     *
     * @param record
     * @return
     * @throws Exception
     */
    @PostMapping("/findByAll")
    public List<Fence> findByAll(@RequestBody Fence record) throws Exception {
        return fenceService.findByAll(record);
    }

    /**
     * 根据条件修改围栏信息
     *
     * @param record
     * @return
     * @throws Exception
     */
    @PostMapping("/updateByPrimaryKeySelective")
    public int updateByPrimaryKeySelective(@RequestBody Fence record) throws Exception {
        return fenceService.updateByPrimaryKeySelective(record);
    }

    /**
     * 根据userId是否存在围栏
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/isHasFenceByUsers", method = RequestMethod.POST)
    public boolean isHasFenceByUsers(@RequestBody Long userId) throws Exception {
        boolean flag = false;
        FenceDTO device = new FenceDTO();
        List<Long> ids = commentService.getUserIds(userId);
        ids.add(userId);
        device.setIds(ids);
        int count = fenceService.findCountByAll(device);
        if (count > 0) {
            flag = true;
        }
        return flag;
    }
}
